package cn.edu.seu.ssny.service.impl;

import cn.edu.seu.ssny.dao.IDeviceCategoryCommonDao;
import cn.edu.seu.ssny.dao.support.IBaseDao;
import cn.edu.seu.ssny.entity.DeviceCategoryCommon;
import cn.edu.seu.ssny.entity.Project;
import cn.edu.seu.ssny.service.IDeviceCategoryCommonService;
import cn.edu.seu.ssny.service.support.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 设备数据表
 */
@Service
public class DeviceCategoryCommonServiceImpl extends BaseServiceImpl<DeviceCategoryCommon, Integer> implements IDeviceCategoryCommonService {

    @Autowired
    private IDeviceCategoryCommonDao deviceCategoryCommonDao;

    @Override
    public IBaseDao<DeviceCategoryCommon, Integer> getBaseDao() {
        return this.deviceCategoryCommonDao;
    }

    @Override
    public List<DeviceCategoryCommon> findByProject(Project project) {
        return deviceCategoryCommonDao.findByProjectOrderByName(project);
    }

    @Override
    public DeviceCategoryCommon findByProjectAndName(Project project, String name) {
        Optional<DeviceCategoryCommon> categoryOptional = deviceCategoryCommonDao.findByProjectAndName(project, name);
        DeviceCategoryCommon category = null;
        if(categoryOptional.isPresent())
            category = categoryOptional.get();
        else
            category = new DeviceCategoryCommon();
            category.setName(name);
            category = saveAndFlush(category, project);
        return category;
    }

    @Override
    public DeviceCategoryCommon saveAndFlush(DeviceCategoryCommon category, Project project) {
        category.setProject(project);
        return saveAndFlush(category);
    }
}